import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:mall/core/models/point_transfer.dart';
import 'package:mall/core/services/new_api.dart';
import 'package:mall/screens/point/point_transfer_query_screen.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

class PointTransferHistoryScreen extends StatefulWidget {
  static const routeName = '/PointTransferHistoryScreen';
  final PointTransferQueryReq args;

  const PointTransferHistoryScreen({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  _PointTransferHistoryScreenState createState() => _PointTransferHistoryScreenState();
}

class _PointTransferHistoryScreenState extends State<PointTransferHistoryScreen> {
  int _pageIndex = 0;
  PointTransferQueryRes _res;
  List<Object> _list = [];

  RefreshController _refreshController;

  @override
  void initState() {
    super.initState();
    _refreshController = RefreshController(initialRefresh: true);
  }

  @override
  void dispose() {
    super.dispose();
    _refreshController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("转赠记录"),
        actions: [
          IconButton(
            icon: Icon(Icons.search),
            onPressed: () => Navigator.of(context).pushReplacementNamed(
              PointTransferQueryScreen.routeName,
            ),
          ),
        ],
      ),
      body: Column(
        children: [
          if (_res != null && _res.statusText != null && _res.statusText.isNotEmpty)
            Container(
              padding: EdgeInsets.all(8.w),
              width: double.infinity,
              color: Colors.white,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text("查询条件"),
                  Text(
                    "${_res.statusText}",
                    style: TextStyle(color: Colors.black54),
                  ),
                ],
              ),
            ),
          Expanded(
            child: _buildSmartRefresher(),
          ),
        ],
      ),
    );
  }

  SmartRefresher _buildSmartRefresher() {
    return SmartRefresher(
      controller: _refreshController,
      child: ListView.separated(
        padding: EdgeInsets.all(8.w),
        itemBuilder: (context, index) {
          final data = _list[index];
          return _buildItem(data);
        },
        separatorBuilder: (context, index) {
          return SizedBox(
            height: 8.w,
          );
        },
        itemCount: _list.length,
      ),
      enablePullUp: _res == null ? false : _res.historyItems.length == 10,
      onRefresh: _onRefresh,
      onLoading: _onLoading,
    );
  }

  void _onRefresh() async {
    _pageIndex = 0;
    final api = context.read<NewApi>();
    try {
      final res = await api.pointTransferQuery(widget.args.copyWith(pageIndex: _pageIndex));
      if (!mounted) {
        return;
      }
      setState(() {
        _res = res;
        _list.clear();
        _list.addAll(res.historyItems);
      });
      _refreshController.refreshCompleted();
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      _refreshController.refreshFailed();
      EasyLoading.showToast("${e.message}");
    }
  }

  void _onLoading() async {
    _pageIndex++;
    final api = context.read<NewApi>();
    try {
      final res = await api.pointTransferQuery(widget.args.copyWith(pageIndex: _pageIndex));
      if (!mounted) {
        return;
      }
      setState(() {
        _res = res;
        _list.addAll(res.historyItems);
      });
      _refreshController.loadComplete();
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      _refreshController.loadFailed();
      EasyLoading.showToast("${e.message}");
    }
  }

  Widget _buildItem(PointTransferQueryItem item) {
    return Container(
      padding: EdgeInsets.all(8.w),
      color: Colors.white,
      child: Column(
        children: [
          Row(
            children: [
              Icon(Icons.access_time_sharp),
              SizedBox(
                width: 4.w,
              ),
              Text("${item.createTime}"),
              Spacer(),
              _buildBorderText(item.accountTypeName),
              SizedBox(
                width: 4.w,
              ),
              _buildBorderText(item.transferFlag),
            ],
          ),
          SizedBox(
            height: 4.w,
          ),
          Row(
            children: [
              Text("赠出账户："),
              Spacer(),
              Text("${item.outUsername}"),
            ],
          ),
          SizedBox(
            height: 4.w,
          ),
          Row(
            children: [
              Text("受赠账户："),
              Spacer(),
              Text("${item.inUsername}"),
            ],
          ),
          SizedBox(
            height: 4.w,
          ),
          Row(
            children: [
              Text("转赠额度："),
              Spacer(),
              Text("${item.amount}"),
            ],
          ),
          SizedBox(
            height: 4.w,
          ),
          Row(
            children: [
              Text("备注："),
              Expanded(
                child: Text(
                  "${item.note}",
                  textAlign: TextAlign.end,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildBorderText(String text) {
    var color = Colors.black87;
    if (text == "受赠") {
      color = Colors.red;
    } else if (text == "赠出") {
      color = Colors.green;
    }
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 4.w),
      decoration: BoxDecoration(
        border: Border.all(color: color),
      ),
      child: Text(
        "$text",
        style: TextStyle(
          color: color,
          fontSize: 12.sp,
        ),
      ),
    );
  }
}
